package com.tuanzi.loan.schedule.receipt.monitor.template;

import com.tuanzi.loan.schedule.receipt.monitor.ISender;
import com.tuanzi.loan.schedule.receipt.monitor.ITemplate;
import com.tuanzi.loan.schedule.receipt.monitor.sender.SenderFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;

public class EmailTemplate implements ITemplate {

    private final JavaMailSender mailSender;
    private final String from;
    private final String to;
    private final String subject;
    private final String content;

    public EmailTemplate(JavaMailSender mailSender, String from, String to, String subject, String content) {
        this.mailSender = mailSender;
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;
    }

    @Override
    public ISender createSender(Object... args) {
        String completedFrom = from;
        String completedTo = to;
        String completedSubject = subject;
        String completedContent = content;

        for (int i = 0; i < args.length; i++) {
            String placeHolder = String.format("[%s]", i);
            String replacement = args[i].toString();
            completedFrom = StringUtils.replace(completedFrom, placeHolder, replacement);
            completedTo = StringUtils.replace(completedTo, placeHolder, replacement);
            completedSubject = StringUtils.replace(completedSubject, placeHolder, replacement);
            completedContent = StringUtils.replace(completedContent, placeHolder, replacement);
        }
        return SenderFactory.createEmailSender(mailSender, completedFrom, completedTo, completedSubject, completedContent);
    }
}
